package config

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/joho/godotenv"
)

// Config 配置结构体
type Config struct {
	// FTP配置
	FTPHost     string
	FTPPort     int
	FTPUser     string
	FTPPassword string
	FTPSecure   bool
	FTPPassive  bool
	FTPTimeout  int
	FTPDebug    bool

	// 路径配置
	LocalAddonPath  string
	LocalAssetsPath string
	RemoteAddonPath string
	RemoteAssetsPath string

	// 同步配置
	WatchMode       bool
	SyncDelay       int
	ExcludePatterns []string
}

// Load 加载配置
func Load() (*Config, error) {
	// 尝试加载.env文件
	if err := godotenv.Load(); err != nil {
		// .env文件不存在不是错误，继续使用环境变量
	}

	config := &Config{}

	// 检查必需的环境变量
	requiredVars := []string{"FTP_HOST", "FTP_USER", "FTP_PASSWORD"}
	var missing []string

	for _, varName := range requiredVars {
		if os.Getenv(varName) == "" {
			missing = append(missing, varName)
		}
	}

	if len(missing) > 0 {
		return nil, fmt.Errorf("缺少必要的环境变量: %s\n请复制 .env.example 为 .env 并填入正确的配置信息", strings.Join(missing, ", "))
	}

	// FTP配置
	config.FTPHost = os.Getenv("FTP_HOST")
	config.FTPUser = os.Getenv("FTP_USER")
	config.FTPPassword = os.Getenv("FTP_PASSWORD")

	// 端口配置
	if portStr := os.Getenv("FTP_PORT"); portStr != "" {
		if port, err := strconv.Atoi(portStr); err == nil {
			config.FTPPort = port
		} else {
			config.FTPPort = 21
		}
	} else {
		config.FTPPort = 21
	}

	// 布尔配置
	config.FTPSecure = os.Getenv("FTP_SECURE") == "true"
	config.FTPPassive = os.Getenv("FTP_PASSIVE") != "false"
	config.FTPDebug = os.Getenv("FTP_DEBUG") == "true"

	// 超时配置
	if timeoutStr := os.Getenv("FTP_TIMEOUT"); timeoutStr != "" {
		if timeout, err := strconv.Atoi(timeoutStr); err == nil {
			config.FTPTimeout = timeout
		} else {
			config.FTPTimeout = 30000
		}
	} else {
		config.FTPTimeout = 30000
	}

	// 路径配置
	config.LocalAddonPath = getAbsPath(os.Getenv("LOCAL_ADDON_PATH"), "../gs_demo_thinkphp/addons/gs_demo")
	config.LocalAssetsPath = getAbsPath(os.Getenv("LOCAL_ASSETS_PATH"), "../gs_demo_thinkphp/public/assets/addons/gs_demo")
	config.RemoteAddonPath = getEnvOrDefault("REMOTE_ADDON_PATH", "/addons/gs_demo")
	config.RemoteAssetsPath = getEnvOrDefault("REMOTE_ASSETS_PATH", "/public/assets/addons/gs_demo")

	// 同步配置
	config.WatchMode = os.Getenv("WATCH_MODE") != "false"

	if delayStr := os.Getenv("SYNC_DELAY"); delayStr != "" {
		if delay, err := strconv.Atoi(delayStr); err == nil {
			config.SyncDelay = delay
		} else {
			config.SyncDelay = 1000
		}
	} else {
		config.SyncDelay = 1000
	}

	// 排除模式
	if patterns := os.Getenv("EXCLUDE_PATTERNS"); patterns != "" {
		config.ExcludePatterns = strings.Split(patterns, ",")
		for i, pattern := range config.ExcludePatterns {
			config.ExcludePatterns[i] = strings.TrimSpace(pattern)
		}
	} else {
		config.ExcludePatterns = []string{
			"node_modules",
			".git",
			".DS_Store",
			"*.log",
			"*.tmp",
			"Thumbs.db",
		}
	}

	return config, nil
}

// getAbsPath 获取绝对路径
func getAbsPath(envPath, defaultPath string) string {
	if envPath == "" {
		envPath = defaultPath
	}
	
	absPath, err := filepath.Abs(envPath)
	if err != nil {
		return envPath
	}
	return absPath
}

// getEnvOrDefault 获取环境变量或默认值
func getEnvOrDefault(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// Display 显示配置信息
func (c *Config) Display() {
	fmt.Printf("配置信息:\n")
	fmt.Printf("  FTP服务器: %s:%d\n", c.FTPHost, c.FTPPort)
	fmt.Printf("  用户名: %s\n", c.FTPUser)
	fmt.Printf("  本地插件: %s\n", c.LocalAddonPath)
	fmt.Printf("  远程插件: %s\n", c.RemoteAddonPath)
	fmt.Printf("  本地资源: %s\n", c.LocalAssetsPath)
	fmt.Printf("  远程资源: %s\n", c.RemoteAssetsPath)
	fmt.Printf("  监控模式: %t\n", c.WatchMode)
	fmt.Printf("  同步延迟: %dms\n", c.SyncDelay)
	fmt.Printf("  排除模式: %s\n", strings.Join(c.ExcludePatterns, ", "))
	fmt.Println()
}
